package com.wsseieiei.fireballgame.items;

import com.wsseieiei.fireballgame.Main;
import com.wsseieiei.fireballgame.entity.EntityBall2test;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;

public class ItemBall extends Item {
    public ItemBall(Properties p_41383_) {
        super(p_41383_);
    }

    public ItemBall() {
        super(new ItemBall.Properties().tab(Main.FIREBALL_GAME_TAB).stacksTo(1));
    }

    protected ItemStack findAmmo(Player player) {
        if (this.isBall2test(player.getItemInHand(InteractionHand.OFF_HAND))) {
            return player.getItemInHand(InteractionHand.OFF_HAND);
        } else if (this.isBall2test(player.getItemInHand(InteractionHand.MAIN_HAND))) {
            return player.getItemInHand(InteractionHand.MAIN_HAND);
        } else {
            for (int i = 0; i < player.getInventory().getContainerSize(); ++i) {
                ItemStack itemstack = player.getInventory().getItem(i);
                if (this.isBall2test(itemstack)) {
                    return itemstack;
                }
            }
            return ItemStack.EMPTY;
        }
    }

    protected boolean isBall2test(ItemStack stack) {
        return stack.getItem() instanceof ItemBall;
    }

    public InteractionResultHolder<ItemStack> use(Level level, Player playerIn, InteractionHand handIn) {
        ItemStack itemstack = playerIn.getItemInHand(handIn);
        boolean flag = !this.findAmmo(playerIn).isEmpty();
        InteractionResultHolder<ItemStack> ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, level, playerIn, handIn, flag);
        if (ret != null) return ret;
        level.playSound((Player)null, playerIn.getX(), playerIn.getY(), playerIn.getZ(), SoundEvents.SNOWBALL_THROW, SoundSource.NEUTRAL, 0.5F, 0.4F / (level.getRandom().nextFloat() * 0.4F + 0.8F));
        if (!playerIn.getAbilities().instabuild && !flag) {
            return InteractionResultHolder.fail(itemstack);
        } else {
            playerIn.startUsingItem(handIn);
            EntityBall2test snowball = new EntityBall2test(playerIn.level,playerIn);
            snowball.setItem(itemstack);
            snowball.shootFromRotation(playerIn, playerIn.getXRot(), playerIn.getYRot(), 0.0F, 1.5F, 1.0F);
            level.addFreshEntity(snowball);
//            playerIn.getCooldowns().addCooldown(this,20);
            itemstack.shrink(1);
            if (itemstack.isEmpty()) {
                playerIn.getInventory().removeItem(itemstack);
            }
            return InteractionResultHolder.consume(itemstack);
        }
    }
}
